<?php
/**
 * Created by PhpStorm.
 * User: 我想有个家
 * Date: 2019/11/30
 * Time: 15:56
 */

namespace App\Lib;


use App\Model\AuRule;
use Hyperf\DbConnection\Db;
use Psr\SimpleCache\CacheInterface;

class MenuAuth {

    /**
     * @var CacheInterface
     */
    private $cache;

    function __construct(CacheInterface $cache) {
        $this->cache = $cache;
    }

    /**
     * 缓存全部菜单
     * @return array
     */
    public function cache(): array {
        $muens = AuRule::query()
            ->where('status', 1)
            ->orderBy('sequence', 'desc')
            ->select('id', 'parent_id', 'name', 'auth', 'path', 'icon')
            ->get()->toArray();
        $this->cache->set('all_menus', $muens);
        return $muens;
    }

    /**
     * 删除用户菜单缓存
     * @param $role
     */
    public function clearAdminCache($role) {
        // 查询拥有该角色的用户
        $users = Db::table('au_admin_role')
            ->where('role_id', $role)
            ->pluck('user_id')->toArray();
        // 删除用户缓存
        foreach ($users as $user) {
            $this->cache->delete("admin_menu_{$user}");
        }
    }

    /**
     * 权限判断，返回true表示鉴权失败
     * @param $uid
     * @param $path
     * @return bool
     */
    public function check($uid, $path) {
        $menus = $this->cache->get("admin_menu_{$uid}");
        if (empty($menus)) {
            $menus = $this->cacheMenu($uid);
        }
        foreach ($menus as $menu) {
            $menu['auth'] = explode("\n", $menu['auth']);
            if (in_array($path, $menu['auth'])) {
                return false;
            }
        }
        return true;
    }

    /**
     * 缓存用户所拥有的菜单
     * @param $uid
     * @return array
     */
    public function cacheMenu($uid) {
        // 全部缓存
        $all = $this->cache->get('all_menus');
        if (empty($all)) {
            // 缓存全部菜单
            $all = $this->cache();
        }
        if ($uid == 1) {
            return $all;
        } else {
            $my = Db::table('au_admin_role as ar')
                ->join('au_role_rule as rr', 'ar.role_id', '=', 'rr.role_id')
                ->join('au_role as r', 'ar.role_id', '=', 'r.id')
                ->where('user_id', $uid)
                ->where('r.status', 1)
                ->pluck('permission_id')->toArray();
            // 拥有的菜单
            $menus = [];
            foreach ($all as $item) {
                if (in_array($item['id'], $my)) {
                    $menus[] = $item;
                }
            }
            $this->cache->set("admin_menu_{$uid}", $menus);
        }
        return $menus;
    }
}
